﻿using AutoMapper;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using Reporting.API.Application.Commands.ProductionPlans;
using Reporting.API.DTOs.ProductionPlanDTO;
using Reporting.API.Utils;
using Reporting.Domain;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.ProductionPlans;
using Reporting.Infrastructure.Interfaces.Sourcetypes;

namespace Reporting.API.Application.CommandHandler.ProductionPlans
{
    public class GetProductionPlanCommandHandler : IRequestHandler<GetProductionPlanCommand, ApiResult<PagingResult<IList<ProductionPlanResponse>>>>
    {
        private readonly IProductionPlanRepository _productionPlanRepository;
        private readonly ISourcetypeRepository _sourcetypeRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetProductionPlanCommandHandler> _logger;

        public GetProductionPlanCommandHandler(ILogger<GetProductionPlanCommandHandler> logger, IMapper mapper, IProductionPlanRepository productionPlanRepository, ISourcetypeRepository sourcetypeRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _productionPlanRepository = productionPlanRepository;
            _sourcetypeRepository = sourcetypeRepository;
        }

        public async Task<ApiResult<PagingResult<IList<ProductionPlanResponse>>>> Handle(GetProductionPlanCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有生产计划
                var productionPlans = await _productionPlanRepository.GetAllAsync();
                // 来源类型（外健）
                var SourcetypePlans = await _sourcetypeRepository.GetAllAsync();


                // 外健链接
                var result = from ProductionPlan in productionPlans
                             join Sourcetype in SourcetypePlans on ProductionPlan.SourcetypeID equals Sourcetype.SourcetypeID
                             select new ProductionPlanResponse
                             {
                                 Productionplanid = ProductionPlan.Productionplanid,
                                 Plannumber = ProductionPlan.Plannumber,
                                 Planname = ProductionPlan.Planname,
                                 Quantityofworkorders = ProductionPlan.Quantityofworkorders,
                                 SourcetypeID = ProductionPlan.SourcetypeID,
                                 Productname = ProductionPlan.Productname,
                                 Productnumber = ProductionPlan.Productnumber,
                                 Specificationandmodel = ProductionPlan.Specificationandmodel,
                                 Unit = ProductionPlan.Unit,
                                 Plannedquantity = ProductionPlan.Plannedquantity,
                                 Plannedcommencementdate = ProductionPlan.Plannedcommencementdate,
                                 Plannedcompletiondate = ProductionPlan.Plannedcompletiondate,
                                 Requirementdate = ProductionPlan.Requirementdate,
                                 State = ProductionPlan.State,
                                 SourcetypeName = Sourcetype.SourcetypeName  // 从关联的 Sourcetype 中获取名称
                             };

                //条件查询
                //计划编号/名称
                if (!string.IsNullOrEmpty(request.PlannumberPlanname))
                {
                    result = result.Where(x => x.Plannumber == request.PlannumberPlanname || x.Planname == request.PlannumberPlanname);
                }
                //来源类型
                if (request.SourcetypeID != null)
                {
                    result = result.Where(x => x.SourcetypeID == request.SourcetypeID);
                }
                //产品名称
                if (!string.IsNullOrEmpty(request.Productname))
                {
                    result = result.Where(x => x.Productname.Contains(request.Productname));
                }
                //状态
                if (request.State != null)
                {
                    result = result.Where(x => x.State == request.State);
                }




                // 当前页的数据
                var currentData = _mapper.Map<IList<ProductionPlanResponse>>(result.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize).ToList());

                // 分页
                var pagingResult = new PagingResult<IList<ProductionPlanResponse>>
                {
                    TotalCount = result.Count(),
                    TotalPage = Math.Ceiling(result.Count() / (double)request.PageSize),
                    Data = currentData
                };

                // 返回成功结果
                return ApiResult<PagingResult<IList<ProductionPlanResponse>>>.Success(pagingResult, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询失败");

                // 返回失败结果
                return ApiResult<PagingResult<IList<ProductionPlanResponse>>>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }
    }
}
